﻿using System;
using System.Web;
using System.Web.Security;
using Medianamik.Core;
using Medianamik.Core.Action;
using Medianamik.Core.Logging;
using Medianamik.Core.Security;
using Medianamik.Service.ActiveDirectory.Configuration;
using Medianamik.Service.ActiveDirectory.Registratrion;
using Medianamik.Service.ActiveDirectory.Service;
using StructureMap;

namespace Medianamik.Service.ActiveDirectory.Action
{
    public class AuthenticationActionHandler : IActionHandler
    {
        private ILogger _logger;
        private ILogger Logger
        {
            get
            {
                return _logger ?? 
                    (_logger = new ObjectFactory<ILogger>().Get("ActionManagerLogger"));
            }
        }

        public void Initialize(ActionManager events)
        {
            ObjectFactory.Initialize(container =>
                 {
                     container.AddRegistry<RepositoryRegistry>();
                     container.AddRegistry<ServiceRegistry>();
                 });

            events.AuthenticationRequested += AuthenticationRequested;
        }

        private void AuthenticationRequested(ActionEventArgs<object> obj)
        {
            var domainUserName = Environment.UserName;
            var membershipService = new Container(new ServiceRegistry()).GetInstance<IMembershipService>();

            if (membershipService.UserCanLogin(domainUserName))
            {
                Logger.Trace("Dans le if membershipService.UserCanLogin(domainUserName)");
                string errorMessage;
                membershipService.SetupUserPermissions(domainUserName);
                
                if (LoginService.UserIsValid(domainUserName, out errorMessage))
                {
                    Logger.Trace("Dans le if LoginService.UserIsValid(domainUserName, out errorMessage) : " + errorMessage);
                    var config = new Container(new ServiceRegistry()).GetInstance<IActiveDirectoryConfigService>();

                    FormsAuthentication.SetAuthCookie(domainUserName, false);
                    LoginService.SetProfileLastActivity(domainUserName);
                    HttpContext.Current.Response.Redirect(config.RedirectUrlWhenLogged);
                }

                Logger.Trace("Ne rentre pas dans le if LoginService.UserIsValid(domainUserName, out errorMessage) : " + errorMessage);
            }

            Logger.Trace("Ne rentre pas dans le if membershipService.UserCanLogin(domainUserName)");
        }

        public string Description
        {
            get { return "Permet l'authentification automatique à l'aide de l'active directory"; }
        }
    }
}
